package com.bloveoacom.weichi;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.KeyEvent;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.StringUtils;
import com.bloveoacom.base.BaseActivity;
import com.bloveoacom.base.BaseFragment;
import com.bloveoacom.base.UserInfoBean;
import com.bloveoacom.http.HttpMethods;
import com.bloveoacom.http.MessageModel;
import com.bloveoacom.http.RxBus;
import com.bloveoacom.http.RxHelper;
import com.bloveoacom.observer.BaseSubscriber2;
import com.bloveoacom.util.AppManager;
import com.bloveoacom.util.AppUtil;
import com.bloveoacom.util.ToastUtil;
import com.bloveoacom.weichi.activity.SettingActivity;
import com.bloveoacom.weichi.bean.FirBean;
import com.bloveoacom.weichi.fragment.ActivityFragment;
import com.bloveoacom.weichi.fragment.MineFragment;
import com.bloveoacom.weichi.fragment.PostListFragment;
import com.bloveoacom.weichi.fragment.PostParentFragment;
import com.bloveoacom.weight.NoScrollViewPager;
import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;

import java.util.Iterator;
import java.util.Set;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.bloveoacom.http.MessageModel.BUY_OK;
import static com.bloveoacom.http.MessageModel.TU_TYPE_EXIT;
import static com.bloveoacom.http.MessageModel.TU_TYPE_LOGIN;
import static com.bloveoacom.http.MessageModel.TU_TYPE_UPDATEUSERINFO;


public class MainActivity extends BaseActivity {

    @BindView(R.id.bottom_navigation_bar)
    BottomNavigationViewEx mBottomNavigationBar;
    @BindView(R.id.fl_container)
    NoScrollViewPager mFlContainer;
    private MainPagerAdapter adapter;
    private BaseFragment[] fragments = new BaseFragment[3];
    private long exitTime = 0;

    private int wc = 0,hd = 1,my = 2;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        initBottom();
    }

    @Override
    public void initData() {
        HttpMethods.getInstance().getHttpService().latest().compose(RxHelper.io_main()).subscribeWith(new BaseSubscriber2<FirBean>(this) {
            @Override
            public void onNext(FirBean bean) {
                if(bean.version> AppUtil.getCurrentVersion(mContext).versionCode){
                    new MaterialDialog.Builder(MainActivity.this)
                            .title("有新版本" + bean.versionShort)
                            .content("版本更新" + AppUtil.getCurrentVersion(mContext).versionName)
                            .positiveText("安装")
                            .negativeText("取消")
                            .onPositive((dialog, which) -> {
                                try {
                                    Intent intent = new Intent();
                                    intent.setAction("android.intent.action.VIEW");
                                    Uri content_url = Uri.parse(bean.installUrl);
                                    intent.setData(content_url);
                                    intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
                                    startActivity(intent);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Uri uri = Uri.parse(bean.installUrl);
                                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                    startActivity(intent);
                                }
                            })
                            .show();
                }
            }
        });
    }

    @Override
    public void getBundleExtras(Bundle extras) {

    }

    private void initBottom() {
        mBottomNavigationBar.enableAnimation(true);
        mBottomNavigationBar.enableShiftingMode(false);
        mBottomNavigationBar.enableItemShiftingMode(false);
        mFlContainer.setOffscreenPageLimit(3);
        adapter = new MainPagerAdapter(getSupportFragmentManager());
        mFlContainer.setAdapter(adapter);
        mBottomNavigationBar.setupWithViewPager(mFlContainer);
        mFlContainer.setCurrentItem(0);
    }
    @Override
    public void initListener() {
        Disposable subscribe = RxBus.getInstance().subscribe(MessageModel.class, new Consumer<MessageModel>() {
            @Override
            public void accept(MessageModel messageModel) throws Exception {
                if (messageModel.type == TU_TYPE_LOGIN ) {
                    //登录
                    ((MineFragment) adapter.getItem(my)).setUserinfo();
                }else if(messageModel.type==TU_TYPE_EXIT){
                    //退出登录
                    ((MineFragment) adapter.getItem(my)).setUserinfo();

                }else if(messageModel.type==TU_TYPE_UPDATEUSERINFO){
                    ((MineFragment) adapter.getItem(my)).setUserinfo();
                }else if(messageModel.type==BUY_OK){
                    ((ActivityFragment) adapter.getItem(hd)).refresh();
                }
            }
        });
        addDispose(subscribe);
    }

    class MainPagerAdapter extends FragmentPagerAdapter {
        public MainPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            BaseFragment fragment = null;
            switch (i) {
                case 0:
                    if (fragments[0] == null) {
                        fragment = PostParentFragment.newInstance();
                        fragments[0] = fragment;
                    } else {
                        fragment = fragments[0];
                    }
                    break;
                case 1:
                    if (fragments[1] == null) {
                        fragment = ActivityFragment.newInstance();
                        fragments[1] = fragment;
                    } else {
                        fragment = fragments[1];
                    }
                    break;
                case 2:
                    if (fragments[2] == null) {
                        fragment = MineFragment.newInstance();
                        fragments[2] = fragment;
                    } else {
                        fragment = fragments[2];
                    }
                    break;
            }
            return fragment;
        }

        @Override
        public int getCount() {
            return 3;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtil.makeShortText(mContext, R.string.press_once_again_exit_app);
                exitTime = System.currentTimeMillis();
            } else {
                AppManager.getAppManager().appExit();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


}
